package com.lzm.listendemo.view.ripple;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.view.View;
import android.view.ViewGroup;

public class MyAnimatorThemeView extends View {
    private Paint paint;
    private Bitmap bg;
    private ViewGroup rootView;
    private boolean start=false;
    private float center_x = 0,center_y = 0;
    private int radius=0,totalRadius=3000,perRadius=55;   //当前已绘制的圆的半径；需要绘制出的圆的半径;每次绘制的半径

    public MyAnimatorThemeView(Context context){
        super(context);
        init();
    }

    private void init(){
        paint=new Paint();
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //是否开始绘制
        if(!start)return;
        //如果已绘制的半径超过需要绘制的半径，则绘制完毕
        if(radius>totalRadius){
            animateFinish();
            return;
        }
        //在新的图层上面绘制
        int layer = canvas.saveLayer(0, 0, getWidth(), getHeight(), null);
        canvas.drawBitmap(bg, 0, 0, null);
        canvas.drawCircle(center_x, center_y, radius+perRadius, paint);
        radius+=perRadius;
        canvas.restoreToCount(layer);
        postInvalidateDelayed(5);
    }

    public void setCenterXY(float cx,float cy){
        this.center_x = cx;
        this.center_y = cy;
    }

    //开启动画
    public void start(){
        if(!start){
            createBg();
            start=true;
            invalidate();
        }
    }

    //将View当前的样式截图保存在bg中
    private void createBg(){
        rootView=(ViewGroup)((Activity)getContext()).getWindow().getDecorView();
        totalRadius= Math.max(rootView.getMeasuredWidth(), rootView.getMeasuredHeight());
        rootView.setDrawingCacheEnabled(true);
        bg=Bitmap.createBitmap(rootView.getDrawingCache(), 0, 0, rootView.getMeasuredWidth(), rootView.getMeasuredHeight());
        rootView.setDrawingCacheEnabled(false);
        attachToRootView();
    }

    //当前View添加到布局中
    private void attachToRootView() {
        if(this.getParent()==null){
            this.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            rootView.addView(this);
        }
    }

    //绘制完毕，动画结束
    private void animateFinish(){
        start=false;
        bg.recycle();
        radius=0;
    }

    //向外提供检查是否开始的方法
    public boolean hasStart(){
        return start;
    }
}
